import React, { useEffect, useState, useImperativeHandle } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Select, Space } from 'antd';
import theme from '../../../../config/theme';
import PropTypes from 'prop-types';
const { Option } = Select;
const mForm = ({ FormConfig, getForm, cRef, resetForm }) => {
  const { colNum, cols } = FormConfig;
  const [form] = Form.useForm();
  let xform = {};
  const [expand, setExpand] = useState(false);
  let list = [];
  const formStyle = {
    maxWidth: 'none',
    background: theme['@search-form-bg'],
    borderRadius: 4,
    padding: 24,
    marginBottom: 20,
  };
  const calcCols = () => {
    /* 默认一行展示4个 */
    const span = colNum ? 24 / colNum : 6;
    for (let index = 0; index < cols.length; index++) {
      const item = cols[index];
      xform[item.formKey] = item.value || '';
      item.span = span;
    }
    /* 计算一行显示的数量 */
    for (let i = 0, length = cols.length; i < length; i += colNum) {
      list.push(cols.slice(i, i + colNum));
    }
    let children = [];
    if (expand) {
      /* 展开全部表单 */
      children = list?.map((item, i) => {
        return (
          <Row key={i} gutter={24}>
            {getCols(item)}
          </Row>
        );
      });
    } else {
      /* 只展示第一行表单 */
      const _list = JSON.parse(JSON.stringify(list));
      _list[0].pop();
      _list[0].push(list[list.length - 1][list[list.length - 1].length - 1]);
      const arr = JSON.parse(JSON.stringify([_list[0]]));
      children = arr?.map((item, i) => {
        return (
          <Row key={i} gutter={24}>
            {getCols(item)}
          </Row>
        );
      });
    }
    return children;
  };
  useEffect(() => {
    calcCols();
  }, [expand]);
  const getCols = (item) => {
    const childs = [];
    const isShow = list && list.length > 1;
    const btns = isShow ? (
      <Space size="small">
        <Button type="primary" htmlType="submit">
          搜索
        </Button>
        <Button
          onClick={() => {
            form.resetFields();
            resetForm && typeof resetForm === 'function' && resetForm();
          }}
        >
          重置
        </Button>
        <a
          href="#"
          style={{
            fontSize: 12,
          }}
          onClick={() => {
            setExpand(!expand);
          }}
        >
          <DownOutlined rotate={expand ? 180 : 0} /> {expand ? '收起' : '展开'}
        </a>
      </Space>
    ) : (
      <Space size="small">
        <Button type="primary" htmlType="submit">
          搜索
        </Button>
        <Button
          onClick={() => {
            form.resetFields();
            resetForm && typeof resetForm === 'function' && resetForm();
          }}
        >
          重置
        </Button>
      </Space>
    );
    for (let i = 0; i < item.length; i++) {
      const obj = item[i];
      childs.push(
        <Col span={obj.span} key={i}>
          {obj['type'] === 'btns' ? (
            btns
          ) : (
            <Form.Item name={obj['formKey']} label={obj['label']}>
              {getComponent(obj['type'], obj)}
            </Form.Item>
          )}
        </Col>,
      );
    }
    return childs;
  };
  /* 获取组件实例 */
  function getComponent(type, item) {
    let component = null;
    switch (type) {
      case 'input':
        component = <Input placeholder="请输入" />;
        break;
      case 'select':
        component = (
          <Select placeholder="请选择" allowClear>
            {item.propsConfig?.list.map((v, i) => (
              <Option key={i} value={v.value}>
                {v.label}
              </Option>
            ))}
          </Select>
        );
        break;
      default:
        component = '';
    }
    return component;
  }
  const onFinish = (values) => {
    getForm(values);
  };
  /* 子组件暴露对应属性或方法供父组件调用 */
  useImperativeHandle(cRef, () => ({
    form,
  }));
  return (
    <Form
      form={form}
      style={formStyle}
      onFinish={onFinish}
      initialValues={xform}
    >
      {calcCols()}
    </Form>
  );
};
mForm.propTypes = {
  FormConfig: PropTypes.object,
};
/* 传值的默认值设置 */
mForm.defaultProps = {
  FormConfig: {},
};
export default mForm;
